package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    public StrategyDetail get(Long id) {
        return strategyDetailMapper.selectByPrimaryKey(id);
    }

    public StrategyContent getContent(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public void saveOrUpdate(StrategyDetail entity) {
        Date d = new Date();
        //设置发布时间
        if (entity.getState() == StrategyDetail.STATE_RELEASE) {
            entity.setReleaseTime(d);
        }
        //设置序列
        if (entity.getSequence() == null) {
            Integer sequence = strategyDetailMapper.selectMaxSequence(entity.getCatalog().getId());
            entity.setSequence(sequence != null ? sequence + 1 : 1);
        }
        StrategyContent content = entity.getStrategyContent();
        if (entity.getId() == null) {
            //处理创建时间
            entity.setCreateTime(d);
            strategyDetailMapper.insert(entity);
            //设置主键关联的id
            content.setId(entity.getId());
            contentMapper.insert(content);
        } else {
            strategyDetailMapper.updateByPrimaryKey(entity);
            content.setId(entity.getId());
            contentMapper.updateByPrimaryKey(content);
        }
    }

    public PageInfo<StrategyDetail> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo<>(list);
    }
}
